package com.kqkj.dyrule.engine.router;

import com.kqkj.dyrule.engine.beans.EventBean;
import com.kqkj.dyrule.engine.beans.EventParam;
import com.kqkj.dyrule.engine.beans.EventSequenceParam;
import com.kqkj.dyrule.engine.beans.RuleConditions;
import com.kqkj.dyrule.engine.queryService.ClickHouseQueryServiceImpl;
import com.kqkj.dyrule.engine.queryService.HbaseQueryServiceImpl;
import com.kqkj.dyrule.engine.util.ConnectionUtils;
import com.kqkj.dyrule.engine.util.EventParamComparator;
import org.apache.hadoop.hbase.client.Connection;

import java.util.List;
import java.util.Map;

/**
 * 只从clickhouse查询
 */
public class SimpleQueryRounter {
    Connection hbaseConnection;
    HbaseQueryServiceImpl hbaseQueryService;

    java.sql.Connection ckConnection;
    ClickHouseQueryServiceImpl clickHouseQueryService;

    public SimpleQueryRounter() throws Exception {
        //获取hbase连接
        hbaseConnection = ConnectionUtils.getHbaseConnection();
        hbaseQueryService = new HbaseQueryServiceImpl(hbaseConnection);
        //获取clickhouse连接
        ckConnection = ConnectionUtils.getCkConnection();
        clickHouseQueryService = new ClickHouseQueryServiceImpl(ckConnection);
    }

    public boolean ruleMatch(RuleConditions rule, EventBean eventBean) throws Exception {
        //判断当前事件是否为规则触发事件
        if(!EventParamComparator.compare(rule.getTriggerEvent(),eventBean)) return false;
        //计算画像条件是否满足
        Map<String, String> userProfileConditions = rule.getUserProfileConditions();
        Boolean profileQueryResult = false;
        if (userProfileConditions != null){
            profileQueryResult = hbaseQueryService.queryProfileConnection(eventBean.getDeviceId(), userProfileConditions);
            if (!profileQueryResult) return false;
        }

        //行为次数条件是否满足
        List<EventParam> actionCountConditions = rule.getActionCountConditions();

        if (actionCountConditions != null && actionCountConditions.size() > 0) {
            for (EventParam actionCountCondition : actionCountConditions) {
                long l = clickHouseQueryService.queryEventCountCondition(eventBean.getDeviceId(), actionCountCondition);
                if (l < actionCountCondition.getCountThresHold()) return false;
            }
        }
        //行为序列次数是否满足
        List<EventSequenceParam> actionSequenceCondition = rule.getActionSequenceCondition();
        if (actionSequenceCondition != null && actionSequenceCondition.size() >0){
            for (EventSequenceParam eventSequenceParam : actionSequenceCondition) {
                int maxStep = clickHouseQueryService.queryEventSequenceCondition(eventBean.getDeviceId(), eventSequenceParam);
                if (maxStep < eventSequenceParam.getEventSequence().size()) return false;
            }
        }
        return true;
    }
}
